<template>
  <div class="knowledge-workspace">
    <header class="workspace-header">
      <div class="header-left">
        <div class="title-block">
          <h2>知识库</h2>
          <p class="subtitle">管理和分享项目文档与知识资源</p>
        </div>
      </div>
      <div class="header-right">
        <el-button 
          text
          class="refresh-button"
          @click="handleRefresh"
        >
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
        <el-button 
          type="primary" 
          class="create-button"
          @click="handleCreateFile"
        >
          <el-icon><Plus /></el-icon>
          上传文件
        </el-button>
      </div>
    </header>

    <div class="workspace-main">
      <!-- 文件夹树（侧边栏） -->
      <aside class="folder-sidebar" :class="{ 'is-collapsed': sidebarCollapsed }">
            <KnowledgeFolderTree
              ref="folderTreeRef"
              :current-folder-id="currentFolderId"
              @folder-selected="handleFolderSelected"
              @create-folder="handleCreateFolder"
              @edit-folder="handleEditFolder"
              @upload-file="handleUploadToFolder"
            />
      </aside>

      <!-- 侧边栏展开/收拢按钮 -->
      <el-button
        text
        class="sidebar-toggle"
        :class="{ 'is-collapsed': sidebarCollapsed }"
        @click="toggleSidebar"
        :title="sidebarCollapsed ? '展开侧边栏' : '收拢侧边栏'"
      >
        <el-icon><DArrowLeft v-if="!sidebarCollapsed" /><DArrowRight v-else /></el-icon>
      </el-button>

      <!-- 主内容区 -->
      <section class="workspace-content">
        <KnowledgeFileList
          :files="files"
          :loading="loading"
          :pagination="pagination"
          @file-click="handleFileClick"
          @preview="handlePreview"
          @edit="handleEdit"
          @share="handleShare"
          @download="handleDownload"
          @move="handleMove"
          @delete="handleDelete"
          @search="handleSearch"
          @filter-change="handleFilterChange"
          @page-change="handlePageChange"
          @page-size-change="handlePageSizeChange"
          @batch-deleted="handleBatchDeleted"
        />
      </section>
    </div>

    <!-- 文件上传对话框 -->
    <KnowledgeFileUpload
      v-model="uploadDialogVisible"
      :default-folder-id="currentFolderId"
      @uploaded="handleFileUploaded"
      @batch-uploaded="handleBatchUploaded"
    />

    <!-- 文件夹创建对话框 -->
    <KnowledgeFolderCreate
      v-model="folderDialogVisible"
      :folder="editingFolder"
      :default-parent-id="creatingFolderParentId"
      @created="handleFolderCreated"
      @updated="handleFolderUpdated"
    />

    <!-- 文件预览对话框 -->
    <KnowledgeFilePreview
      v-model="previewDialogVisible"
      :file="previewingFile || undefined"
      @edit="handleEdit"
    />

    <!-- 文件编辑对话框 -->
    <KnowledgeFileEditor
      v-model="editorDialogVisible"
      :file="editingFile || null"
      @saved="handleFileSaved"
    />

    <!-- 文件分享对话框 -->
    <KnowledgeFileShare
      v-model="shareDialogVisible"
      :file="sharingFile"
      @updated="handleRefresh"
    />

    <!-- 文件夹选择对话框（用于移动文件） -->
    <KnowledgeFolderSelectDialog
      :visible="folderSelectDialogVisible"
      :current-folder-id="movingFile?.folder_id"
      @update:visible="folderSelectDialogVisible = $event"
      @confirm="handleMoveConfirm"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh, Plus, DArrowLeft, DArrowRight } from '@element-plus/icons-vue'
import {
  getKnowledgeFiles,
  getKnowledgeFolders,
  deleteKnowledgeFile,
  downloadKnowledgeFile,
  updateKnowledgeFile,
  type KnowledgeFile,
  type KnowledgeFolder,
  type KnowledgeFileQueryParams
} from '@/api/knowledge'
import { ResponseParser } from '@/utils/responseParser'
import KnowledgeFolderTree from '@/components/knowledge/KnowledgeFolderTree.vue'
import KnowledgeFileList from '@/components/knowledge/KnowledgeFileList.vue'
import KnowledgeFileUpload from '@/components/knowledge/KnowledgeFileUpload.vue'
import KnowledgeFolderCreate from '@/components/knowledge/KnowledgeFolderCreate.vue'
import KnowledgeFilePreview from '@/components/knowledge/KnowledgeFilePreview.vue'
import KnowledgeFileEditor from '@/components/knowledge/KnowledgeFileEditor.vue'
import KnowledgeFileShare from '@/components/knowledge/KnowledgeFileShare.vue'
import KnowledgeFolderSelectDialog from '@/components/knowledge/KnowledgeFolderSelectDialog.vue'

const loading = ref(false)
const files = ref<KnowledgeFile[]>([])
const currentFolderId = ref<string | undefined>()
const sidebarCollapsed = ref(false)

const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

const searchKeyword = ref('')
const fileTypeFilter = ref('')

// 对话框状态
const uploadDialogVisible = ref(false)
const folderDialogVisible = ref(false)
const previewDialogVisible = ref(false)
const editorDialogVisible = ref(false)
const shareDialogVisible = ref(false)
const folderSelectDialogVisible = ref(false)

// 当前操作的文件/文件夹
const previewingFile = ref<KnowledgeFile | undefined>(undefined)
const editingFile = ref<KnowledgeFile | undefined>(undefined)
const sharingFile = ref<KnowledgeFile | undefined>(undefined)
const movingFile = ref<KnowledgeFile | undefined>(undefined)
const editingFolder = ref<any>(null)
const creatingFolderParentId = ref<string | undefined>(undefined)
const folderTreeRef = ref<InstanceType<typeof KnowledgeFolderTree> | null>(null)

// 加载文件列表
const loadFiles = async () => {
  try {
    loading.value = true
    const params: KnowledgeFileQueryParams = {
      page: pagination.page,
      size: pagination.size,
      folder_id: currentFolderId.value,
      search: searchKeyword.value || undefined,
      file_type: fileTypeFilter.value || undefined
    }

    const response = await getKnowledgeFiles(params)
    // 使用 parseListResponse 解析列表响应
    const parsed = ResponseParser.parseListResponse<KnowledgeFile>(response)
    
    // 更新文件列表和分页信息
    files.value = parsed.items || []
    pagination.total = parsed.total || 0
    if (parsed.pagination) {
      pagination.page = parsed.pagination.page || pagination.page
      pagination.size = parsed.pagination.size || pagination.size
    }
  } catch (error: any) {
    console.error('加载文件列表失败:', error)
    ElMessage.error('加载文件列表失败')
    files.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 刷新整个页面
const handleRefresh = async () => {
  // 刷新文件夹树
  if (folderTreeRef.value) {
    folderTreeRef.value.refresh()
  }
  // 先验证当前文件夹是否仍然存在
  await validateCurrentFolder()
  // 然后加载文件列表
  loadFiles()
}

// 创建文件
const handleCreateFile = () => {
  uploadDialogVisible.value = true
}

// 文件上传成功
const handleFileUploaded = () => {
  loadFiles()
}

// 批量上传成功
const handleBatchUploaded = (uploadedFiles: KnowledgeFile[]) => {
  ElMessage.success(`成功上传 ${uploadedFiles.length} 个文件`)
  loadFiles()
}

// 批量删除成功
const handleBatchDeleted = () => {
  loadFiles()
}

// 文件夹选择
const handleFolderSelected = (folderId: string | undefined) => {
  currentFolderId.value = folderId
  pagination.page = 1
  loadFiles()
}

// 验证当前文件夹是否仍然存在
const validateCurrentFolder = async () => {
  if (!currentFolderId.value) return
  
  try {
    const response = await getKnowledgeFolders({ tree: true })
    const parsed = ResponseParser.parseResponse<KnowledgeFolder[]>(response)
    if (parsed.success && parsed.data) {
      const folders = parsed.data || []
      const findFolder = (id: string, folderList: KnowledgeFolder[]): boolean => {
        for (const folder of folderList) {
          if (folder.id === id) return true
          if (folder.children && folder.children.length > 0) {
            if (findFolder(id, folder.children)) return true
          }
        }
        return false
      }
      
      if (!findFolder(currentFolderId.value, folders)) {
        ElMessage.warning('当前选择的文件夹已不存在，已切换到根目录')
        currentFolderId.value = undefined
        loadFiles()
      }
    }
  } catch (error) {
    console.error('验证文件夹失败:', error)
  }
}

// 创建文件夹
const handleCreateFolder = (parentId?: string) => {
  editingFolder.value = null
  // 设置要创建的子文件夹的父文件夹ID
  creatingFolderParentId.value = parentId
  folderDialogVisible.value = true
}

// 编辑文件夹
const handleEditFolder = (folder: KnowledgeFolder) => {
  editingFolder.value = folder
  folderDialogVisible.value = true
}

// 上传文件到指定文件夹
const handleUploadToFolder = (folderId: string) => {
  currentFolderId.value = folderId
  uploadDialogVisible.value = true
}

// 文件夹创建/更新成功
const handleFolderCreated = () => {
  handleRefresh()
}

const handleFolderUpdated = () => {
  handleRefresh()
}

// 文件点击
const handleFileClick = (file: KnowledgeFile) => {
  handlePreview(file)
}

// 预览文件
const handlePreview = (file: KnowledgeFile) => {
  previewingFile.value = file
  previewDialogVisible.value = true
}

// 编辑文件
const handleEdit = (file: KnowledgeFile) => {
  editingFile.value = file
  editorDialogVisible.value = true
  previewDialogVisible.value = false
}

// 文件保存成功
const handleFileSaved = () => {
  handleRefresh()
}

// 分享文件
const handleShare = (file: KnowledgeFile) => {
  sharingFile.value = file
  shareDialogVisible.value = true
}

// 下载文件
const handleDownload = async (file: KnowledgeFile) => {
  try {
    const response = await downloadKnowledgeFile(file.id)
    const blob = new Blob([response.data])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = file.filename
    link.click()
    window.URL.revokeObjectURL(url)
    ElMessage.success('下载成功')
  } catch (error: any) {
    console.error('下载失败:', error)
    ElMessage.error('下载失败')
  }
}

// 移动文件
const handleMove = (file: KnowledgeFile) => {
  movingFile.value = file
  folderSelectDialogVisible.value = true
}

// 确认移动文件
const handleMoveConfirm = async (targetFolderId: string | undefined) => {
  if (!movingFile.value) {
    return
  }

  // 如果目标文件夹与当前文件夹相同，无需移动
  if (movingFile.value.folder_id === targetFolderId) {
    ElMessage.warning('目标文件夹与当前文件夹相同，无需移动')
    folderSelectDialogVisible.value = false
    movingFile.value = undefined
    return
  }

  try {
    const response = await updateKnowledgeFile(movingFile.value.id, {
      folder_id: targetFolderId || undefined
    })
    const parsed = ResponseParser.parseResponse<KnowledgeFile>(response)
    
    if (parsed.success && parsed.data) {
      ElMessage.success('文件移动成功')
      folderSelectDialogVisible.value = false
      movingFile.value = undefined
      // 刷新文件列表
      handleRefresh()
    } else {
      ElMessage.error(parsed.message || '移动失败')
    }
  } catch (error: any) {
    console.error('移动文件失败:', error)
    ElMessage.error(error?.response?.data?.message || error?.message || '移动失败')
  }
}

// 删除文件
const handleDelete = async (file: KnowledgeFile) => {
  try {
    await deleteKnowledgeFile(file.id)
    ElMessage.success('删除成功')
    handleRefresh()
  } catch (error: any) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败')
  }
}

// 搜索
const handleSearch = (keyword: string) => {
  searchKeyword.value = keyword
  pagination.page = 1
  loadFiles()
}

// 筛选变化
const handleFilterChange = (fileType: string) => {
  fileTypeFilter.value = fileType
  pagination.page = 1
  loadFiles()
}

// 分页变化
const handlePageChange = (page: number) => {
  pagination.page = page
  loadFiles()
}

const handlePageSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  loadFiles()
}

// 切换侧边栏
const toggleSidebar = () => {
  sidebarCollapsed.value = !sidebarCollapsed.value
}

// 初始化
onMounted(() => {
  loadFiles()
})
</script>

<style scoped lang="scss">
.knowledge-workspace {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: var(--bg-secondary);
  color: var(--text-primary);
  transition: background-color 0.3s ease, color 0.3s ease;
}

.workspace-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid var(--border-color-light);
  background: var(--bg-card);
  transition: background-color 0.3s ease, border-color 0.3s ease;

  .header-left {
    .title-block {
      h2 {
        margin: 0;
        font-size: 20px;
        font-weight: 600;
        color: var(--text-primary);
        transition: color 0.3s ease;
      }

      .subtitle {
        margin: 4px 0 0 0;
        font-size: 14px;
        color: var(--text-secondary);
        transition: color 0.3s ease;
      }
    }
  }

  .header-right {
    display: flex;
    align-items: center;
    gap: 12px;
  }
}

.workspace-main {
  flex: 1;
  overflow: hidden;
  display: flex;
  position: relative;
}

.folder-sidebar {
  width: 280px;
  flex-shrink: 0;
  transition: width 0.3s, background-color 0.3s ease, border-color 0.3s ease;
  position: relative;
  background: var(--bg-card);
  border-right: 1px solid var(--border-color-light);

  &.is-collapsed {
    width: 0;
    overflow: hidden;
    border-right: none;
  }
}

.sidebar-toggle {
  position: absolute;
  top: 50%;
  z-index: 100;
  background: var(--bg-card);
  border: 1px solid var(--border-color);
  border-radius: 50%;
  width: 32px;
  height: 32px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: var(--shadow-sm);
  transition: left 0.3s, transform 0.3s, background-color 0.3s ease, border-color 0.3s ease, color 0.3s ease;
  cursor: pointer;

  &:hover {
    background: var(--bg-hover);
    border-color: var(--color-primary);
    color: var(--color-primary);
  }

  // 侧边栏展开时，按钮在侧边栏右侧
  &:not(.is-collapsed) {
    left: 280px;
    transform: translateY(-50%) translateX(-50%);
  }

  // 侧边栏收拢时，按钮在屏幕左侧边缘，向左偏移一半使其可见
  &.is-collapsed {
    left: 0;
    transform: translateY(-50%) translateX(-50%);
  }
}

.workspace-content {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  background: var(--bg-card);
  transition: background-color 0.3s ease;
}
</style>
